package com.example.news.widget.bottomtab;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import java.util.ArrayList;

public class BottomTabLayout extends LinearLayout implements View.OnClickListener {
    private ArrayList<TabItem> tabs;
    private OnTabClickListener listener;
    private int tabCount;
    private View selectedView;

    public BottomTabLayout(Context context) {
        super(context);
        initView();
    }

    public BottomTabLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public BottomTabLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        setOrientation(HORIZONTAL);
    }

    public void setCurrentTab(int i) {
        if (i < tabCount && i >= 0) {
            View view = getChildAt(i);
            onClick(view);
        }
    }

    public void initData(ArrayList<TabItem> tabs, OnTabClickListener listener) {
        this.tabs = tabs;
        this.listener = listener;
        LayoutParams params = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
        params.weight = 1;
        params.gravity = Gravity.CENTER;
        if (tabs != null && tabs.size() > 0) {
            tabCount = tabs.size();
            TabView mTabView = null;
            for (int i = 0, len = tabs.size(); i < len; i++) {
                mTabView = new TabView(getContext());
                mTabView.setTag(tabs.get(i));
                mTabView.initData(tabs.get(i));
                mTabView.setOnClickListener(this);
                addView(mTabView, params);
            }
        } else {
            throw new IllegalArgumentException("tabs can not be empty");
        }
    }

    @Override
    public void onClick(View view) {
        if (selectedView != view) {
            listener.onTabClick((TabItem) view.getTag());
            view.setSelected(true);
            if (selectedView != null) {
                selectedView.setSelected(false);
            }
            selectedView = view;
        }
    }

    public interface OnTabClickListener {
        void onTabClick(TabItem tabItem);
    }
}
